﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.IO;
using System.IO.Ports;
using CoreAudioApi;

namespace ConsoleApplication4
{
    public class PortDataReceived
    {
        public static object lockObject = new object();
        public static SerialPort currentPort = null;
        public static string portstring = string.Empty;

        public static string volumeLevel;
        public static string brightnessLevel;
        public static MMDevice device;

        public static void Main()
        {
            string portName = string.Empty;                
            // Initialize the current port in the machine
            if (currentPort == null)
            {
                StreamReader reader = new StreamReader(@"C:\comport.txt");
                portName = reader.ReadLine();
                reader.Close();

                MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
                device = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);                

                if (portName.ToUpper().Contains("COM"))
                {
                    currentPort = new SerialPort(portName);
                    currentPort.BaudRate = 9600;
                    currentPort.Parity = Parity.None;
                    currentPort.StopBits = StopBits.One;
                    currentPort.DataBits = 8;
                    currentPort.Handshake = Handshake.None;
                    currentPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
                    currentPort.Open();
                    Console.ReadKey();
                    currentPort.Close();
                }
                else
                {
                    Console.WriteLine("No port given in registry path c:\\comport.txt");
                    Console.WriteLine("Check if the file and portname exists.");
                }
            }
        }

        private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            lock (lockObject)
            {
                // Serial port read                    
                SerialPort readPort = (SerialPort)sender;

                // Read the input string 
                portstring = readPort.ReadExisting();
                portstring = portstring.ToUpper().Trim();                
                if ((portstring.Contains('L')) && (portstring.Contains('S')) && (portstring.Length >= 8))
                {
                    brightnessLevel = portstring.Substring((portstring.IndexOf("L") + 1), ((portstring.IndexOf("S") - portstring.IndexOf("L") - 1)));
                    volumeLevel = portstring.Substring((portstring.IndexOf("S") + 1), 3);                    

                    if (IsDigitsOnly(volumeLevel))
                    {                        
                        AdjustVolume(volumeLevel);                     
                    }
                    if (IsDigitsOnly(brightnessLevel))
                    {                        
                        AdjustBrightness(brightnessLevel);                     
                    }
                }
            }
        }

        // Function to confirm if the parsed string contains only numbers
        public static bool IsDigitsOnly(string strCheck)
        {
            try
            {
                foreach (char c in strCheck)
                {
                    if (c < '0' || c > '9')
                        return false;
                }
            }
            catch (Exception ex)
            {
                //eventLog1.WriteEntry("Exception occurred as : " + ex.Message);
            }
            return true;
        }

        // Function to Adjust the brightness
        public static void AdjustBrightness(string brightness)
        {
            try
            {
                if (brightness.Length > 0)
                {
                    short bLevel = Convert.ToInt16(brightness);
                    Brightness.SetBrightness(bLevel);
                }
            }
            catch (Exception ex)
            {
                // eventLog1.WriteEntry("Exception occurred as : " + ex.Message);                
            }
        }

        // Function to Adjust the volume
        public static void AdjustVolume(string volume)
        {
            try
            {
                // Setting volume in Windows7
                if (volume.Length > 0)
                {
                    int vLevel = Convert.ToInt32(volume);
                    device.AudioEndpointVolume.MasterVolumeLevelScalar = ((float)vLevel / 255.0f);
                }
            }
            catch (Exception ex)
            {
                //eventLog1.WriteEntry("Exception occurred as : " + ex.Message);                
            }
        }
    }
    
}
